package org.springblade.modules.admin.task;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import liquibase.pro.packaged.E;
import org.springblade.modules.admin.entity.BuildingContract;
import org.springblade.modules.admin.entity.LiftElevator;
import org.springblade.modules.admin.service.BuildingContractService;
import org.springblade.modules.admin.service.LiftElevatorService;
import org.springblade.modules.admin.utils.MailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Jackey
 * @date 2021年11月30日 11:41
 */
@Component
public class LiftCoreDataSyncJob {

	@Autowired
	private Environment environment;
	@Autowired
	private BuildingContractService buildingContractService;
	@Resource
	private LiftElevatorService liftElevatorService;
	@Autowired
	private MailUtil mailUtil;

	/**
	 * 合同数据同步 每天23:45
	 */
	//@Scheduled(cron = "0 45 23 * * ?")
	@XxlJob(value = "contractDataSync")
	private void contractDataSync() {
		XxlJobHelper.handleSuccess("银河合同同步希道-(contractDataSync)-[执行]开始");
		try {
			String[] activeProfiles = environment.getActiveProfiles();
			System.out.println(activeProfiles[0]);

			if ("prod".equals(activeProfiles[0])) {
				List<String> collect = buildingContractService.list().stream().map(BuildingContract::getContractId).collect(Collectors.toList());
				List<String> contractList = new ArrayList<>();
				for (String s : collect) {
					List<String> stringList = StrUtil.split(s, ',');
					contractList.addAll(stringList);
				}

				Map<String, Object> paramMap = new HashMap<>();
				paramMap.put("j_tenantid", 2);
				paramMap.put("j_username", "谢银锋");
				paramMap.put("j_password", "123456");

				Map<String, String> headerMap = new HashMap<>();
				headerMap.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
				headerMap.put("Content-Type", "application/x-www-form-urlencoded");
				headerMap.put("Host", "14.215.246.98:8888");
				headerMap.put("Origin", "http://14.215.246.98:8888");
				headerMap.put("Referer", "http://14.215.246.98:8888/security/html/login.jsp");
				headerMap.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36");

				HttpResponse httpResponse = HttpRequest.post("http://14.215.246.98:8888/j_spring_security_check").form(paramMap).addHeaders(headerMap)
					.execute();
				Map<String, List<String>> headers = httpResponse.headers();
				String nCookieString = headers.get("Set-Cookie").get(0);
				String cookieString = StrUtil.split(nCookieString, ';').get(0);
				headerMap.put("Cookie", "sysbaseVersion=11.9.0; jgsize_maintainContractList=10000; " + cookieString);
				HttpResponse finalResponse = HttpRequest.get("http://14.215.246.98:8888/index.jsp").addHeaders(headerMap)
					.execute();
				String body = HttpRequest.get("http://14.215.246.98:8888/maintain/contractAction!findList.action?state=1&from=maintain&random=0.2112853273481099&_search=true&nd=1638253734172&rows=10000&page=1&sidx=item_id&sord=asc")
					.addHeaders(headerMap)
					.execute().body();
				cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(body);
				JSONArray dataArray = JSONUtil.parseArray(jsonObject.get("data"));

				List<String> idList = dataArray.stream().map(o -> {
					cn.hutool.json.JSONObject data = JSONUtil.parseObj(o);
					return data.get("id").toString();
				}).collect(Collectors.toList());

				//交集
				List<String> resultList = this.intersectionForList(collect, idList);
				if (resultList.size() > 0) {
					List<BuildingContract> list = buildingContractService.list(new LambdaQueryWrapper<BuildingContract>().in(BuildingContract::getContractId, resultList));
					List<Map<String, String>> mapList = new ArrayList<>();
					for (BuildingContract buildingContract : list) {
						String s = buildingContract.getContractId();
						String data = HttpRequest.get("http://14.215.246.98:8888/maintain/liftAction!findList.action?contractId=" + s + "&state=1&from=maintain&random=0.5479617521381546&_search=true&nd=1638257480883&rows=20&page=1&sidx=item_id&sord=asc")
							.addHeaders(headerMap)
							.execute().body();
						cn.hutool.json.JSONObject object = JSONUtil.parseObj(data);
						if (JSONUtil.parseArray(object.get("data")).size() > 0) {
							cn.hutool.json.JSONObject detail = JSONUtil.parseObj(JSONUtil.parseArray(object.get("data")).get(0));
							String contractNo = (String) detail.get("contractNo");
							if (!buildingContract.getContractName().equals(contractNo)) {
								Map<String, String> map = new HashMap<>();
								map.put("contractId", s);
								map.put("contractNo", contractNo);
								mapList.add(map);
							}
						}
					}
					if (mapList.size() > 0) {

						mailUtil.sendSimpleMail("137177384@qq.com", "LiftCore [合同] 有[更新]数据 [增加]", mapList.toString());
					}
				}
				//差集
				idList.removeAll(contractList);
				if (idList.size() > 0) {
					List<Map<String, String>> mapList = new ArrayList<>();
					for (String s : idList) {
						String data = HttpRequest.get("http://14.215.246.98:8888/maintain/liftAction!findList.action?contractId=" + s + "&state=1&from=maintain&random=0.5479617521381546&_search=true&nd=1638257480883&rows=20&page=1&sidx=item_id&sord=asc")
							.addHeaders(headerMap)
							.execute().body();
						cn.hutool.json.JSONObject object = JSONUtil.parseObj(data);
						if (JSONUtil.parseArray(object.get("data")).size() > 0) {
							cn.hutool.json.JSONObject detail = JSONUtil.parseObj(JSONUtil.parseArray(object.get("data")).get(0));
							Map<String, String> map = new HashMap<>();
							map.put("contractId", s);
							map.put("contractNo", (String) detail.get("contractNo"));
							mapList.add(map);
						}

					}
					if (mapList.size() > 0) {

						mailUtil.sendSimpleMail("137177384@qq.com", "LiftCore [合同] 有[新增]数据 [增加]", mapList.toString());
					}
				}
			}
			XxlJobHelper.handleSuccess("银河合同同步希道-(contractDataSync)-[执行]成功");
		} catch (Exception e) {
			XxlJobHelper.handleSuccess("银河合同同步希道-(contractDataSync)-[执行]失败" + e);

		}
	}

	/**
	 * 电梯数据同步 每天23:50
	 */
	//@Scheduled(cron = "0 50 23 * * ?")
	@XxlJob(value = "liftDataSync")
	private void liftDataSync() {
		XxlJobHelper.handleSuccess("中研部电梯信息同步希道-(contractDataSync)-[执行]开始");
		try {
			String[] activeProfiles = environment.getActiveProfiles();
			System.out.println(activeProfiles[0]);

			if ("prod".equals(activeProfiles[0])) {
				List<String> collect = liftElevatorService.list().stream().map(LiftElevator::getLId).collect(Collectors.toList());

				Map<String, Object> paramMap = new HashMap<>();
				paramMap.put("j_tenantid", 2);
				paramMap.put("j_username", "谢银锋");
				paramMap.put("j_password", "123456");

				Map<String, String> headerMap = new HashMap<>();
				headerMap.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
				headerMap.put("Content-Type", "application/x-www-form-urlencoded");
				headerMap.put("Host", "14.215.246.98:8888");
				headerMap.put("Origin", "http://14.215.246.98:8888");
				headerMap.put("Referer", "http://14.215.246.98:8888/security/html/login.jsp");
				headerMap.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36");

				HttpResponse httpResponse = HttpRequest.post("http://14.215.246.98:8888/j_spring_security_check").form(paramMap).addHeaders(headerMap)
					.execute();
				Map<String, List<String>> headers = httpResponse.headers();
				String nCookieString = headers.get("Set-Cookie").get(0);
				String cookieString = StrUtil.split(nCookieString, ';').get(0);
				headerMap.put("Cookie", "sysbaseVersion=11.9.0; jgsize_maintainContractList=10000; " + cookieString);
				HttpResponse finalResponse = HttpRequest.get("http://14.215.246.98:8888/index.jsp").addHeaders(headerMap)
					.execute();


				String body = HttpRequest.get("http://14.215.246.98:8888/maintain/liftAction!findList.action?contractId=&state=1&from=contract&random=0.6129245027313386&_search=true&nd=1638324752218&rows=10000&page=1&sidx=item_id&sord=asc")
					.addHeaders(headerMap)
					.execute().body();
				cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(body);
				JSONArray dataArray = JSONUtil.parseArray(jsonObject.get("data"));

				List<String> idList = dataArray.stream().map(o -> {
					cn.hutool.json.JSONObject data = JSONUtil.parseObj(o);
					return data.get("liftId").toString();
				}).collect(Collectors.toList());

				//差集
				idList.removeAll(collect);

				if (idList.size() > 0) {
					List<Map<String, String>> mapList = new ArrayList<>();
					for (String s : idList) {
						String data = HttpRequest.get("http://14.215.246.98:8888/maintain/liftAction!findList.action?contractId=&state=1&from=contract&random=0.6129245027313386&_search=true&nd=1638325189971&rows=20&page=1&sidx=item_id&sord=asc&liftId=" + s)
							.addHeaders(headerMap)
							.execute().body();
						cn.hutool.json.JSONObject object = JSONUtil.parseObj(data);
						cn.hutool.json.JSONObject detail = JSONUtil.parseObj(JSONUtil.parseArray(object.get("data")).get(0));
						Map<String, String> map = new HashMap<>(3);
						map.put("liftId", s);
						map.put("liftNo", (String) detail.get("liftNo"));
						map.put("liftIDNo", (String) detail.get("liftIDNo"));
						mapList.add(map);
					}
					if (mapList.size() > 0) {
						mailUtil.sendSimpleMail("137177384@qq.com", "LiftCore [电梯] 有新增数据 [增加]", mapList.toString());
					}
				}
			}
			XxlJobHelper.handleSuccess("中研部电梯信息同步希道-(contractDataSync)-[执行]成功");
		} catch (Exception e) {
			XxlJobHelper.handleSuccess("中研部电梯信息同步希道-(contractDataSync)-[执行]失败" + e);
		}
	}

	public List<String> intersectionForList(List<String> arr1, List<String> arr2) {

		List<String> resultList = new ArrayList<>();
		arr1.stream().forEach(a1 -> {
			if (arr2.contains(a1)) {
				resultList.add(a1);
			}

		});
		return resultList;
	}
}
